﻿using DevelopTool.Bll.ChatBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.CommonHelpers;
using DevelopTool.Model.ChatModels;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace DevelopTool.Forms.ChatForms
{
    /// <summary>
    /// 局域网聊天 主界面
    /// </summary>
    public partial class ChatMainForm : BaseUIForm
    {
        private ChatBll chatBll;

        private SearchAndAddUserForm searchAndAddUserForm;

        private ChatSessionControl chatSessionControl;

        public ChatMainForm()
        {
            InitializeComponent();
        }

        private void ChatMainForm_Load(object sender, EventArgs e)
        {
            #region 检查是否已启用聊天功能
            if (!Setting.Chat.Enable || !ChatNetworkBll.CheckChatServiceRunningState())
            {
                this.ShowWarningDialog("提示", $"未开启聊天功能，请在设置中启用聊天功能后再来~", UIStyle.Gray);
                this.Close();
                return;
            }
            #endregion 检查是否已启用聊天功能

            this.chatBll = new ChatBll();

            this.Text = $"{GlobalData.AppName_zh} 局域网聊天";//窗口标题

            SetBtnHelpProperty();//设置窗口右上角扩展按钮属性

            #region 设置控件的Tips
            this.uiToolTip.SetToolTip(this.btnSetting, this.btnSetting.TipsText);
            this.uiToolTip.SetToolTip(this.btnTopMost, this.btnTopMost.TipsText);
            this.uiToolTip.SetToolTip(this.btnRefreshLanUserList, this.btnRefreshLanUserList.TipsText);
            this.uiToolTip.SetToolTip(this.btnAddUser, this.btnAddUser.TipsText);
            #endregion 设置控件的Tips

            this.txtNikeName.Text = Setting.Chat.NikeName;//用户昵称

            ThemHelper.SetSystemThem(this);

            ShowChatSession();

            #region 注册一些事件
            ChatBll.ChatUserChangedEvent += ChatBll_StaticChatUserChangedEvent;
            ChatBll.ChatNewMessageEvent += this.ChatBll_ChatNewMessageEvent;
            ChatNetworkBll.StartSendDiscoveryBroadcast += ChatNetworkBll_StartSendDiscoveryBroadcast;
            ChatNetworkBll.CompleteSendDiscoveryBroadcast += ChatNetworkBll_CompleteSendDiscoveryBroadcast;
            #endregion 注册一些事件
        }



        /// <summary>
        /// 单击用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="button"></param>
        /// <param name="user"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ChatUserItem_ItemClick(object sender, MouseButtons button, ChatUser user)
        {

        }


        /// <summary>
        /// 双击用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="user"></param>
        private void ChatUserItem_ItemDoubleClick(object sender, ChatUser user)
        {
            if (this.chatSessionControl != null && this.chatSessionControl.SessionChatUser.UserId == user.UserId) return;

            this.chatSessionControl?.Dispose();

            this.uiSplitContainer.Panel1.Controls.Clear();

            this.chatSessionControl = new ChatSessionControl(user);
            chatSessionControl.Show();
            chatSessionControl.Dock = DockStyle.Fill;
            this.uiSplitContainer.Panel1.Controls.Add(chatSessionControl);
        }


        /// <summary>
        /// 手动添加好友
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            using (this.searchAndAddUserForm = new SearchAndAddUserForm())
            {
                if (searchAndAddUserForm.ShowDialog() != DialogResult.OK) return;

                AddUserToSessionList(searchAndAddUserForm.ChatUser);
            }
        }

        /// <summary>
        /// 接收到新消息事件
        /// </summary>
        /// <param name="sendChatUser"></param>
        /// <param name="chatRecord"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ChatBll_ChatNewMessageEvent(ChatRecord chatRecord)
        {
            this.BeginInvoke(new Action(() =>
            {
                AddUserToSessionList(chatRecord.SendUser);
            }));
        }


        #region 网络发现相关

        /// <summary>
        /// 刷新局域网用户列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefreshLanUserList_Click(object sender, EventArgs e)
        {
            this.backgroundWorker_SendDiscoveryBroadcast.RunWorkerAsync();
        }

        /// <summary>
        /// 后台发送网络发现广播
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker_SendDiscoveryBroadcast_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            this.btnRefreshLanUserList.TagString = "1";
            ChatNetworkBll.SendDiscoveryBroadcastToAllNetworkSegments();
        }

        /// <summary>
        /// 开始发送网络广播事件
        /// </summary>
        /// <param name="result"></param>
        /// <param name="message"></param>
        private void ChatNetworkBll_StartSendDiscoveryBroadcast(bool result, string message)
        {
            this.BeginInvoke(new Action(() =>
            {
                this.btnRefreshLanUserList.Enabled = false;
                this.btnAddUser.Enabled = false;
            }));
        }


        /// <summary>
        /// 完成发送网络广播事件
        /// </summary>
        /// <param name="result"></param>
        /// <param name="message"></param>
        private void ChatNetworkBll_CompleteSendDiscoveryBroadcast(bool result, string message)
        {
            this.BeginInvoke(new Action(() =>
            {
                //只在手动点击发送时才显示提示
                if (!string.IsNullOrEmpty(this.btnRefreshLanUserList.TagString))
                {
                    if (result)
                    {
                        this.ShowSuccessTip(this.btnRefreshLanUserList, message);
                    }
                    else
                    {
                        this.ShowWarningTip(this, message, 3000);
                    }
                }

                this.btnRefreshLanUserList.Enabled = true;
                this.btnRefreshLanUserList.TagString = string.Empty;

                this.btnAddUser.Enabled = true;

                ShowChatSession();
            }));
        }


        /// <summary>
        /// 用户信息改变事件
        /// </summary>
        /// <param name="chatUser"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ChatBll_StaticChatUserChangedEvent(ChatUser chatUser)
        {
            this.BeginInvoke(new Action(() =>
            {
                if (this.chatSessionControl != null && !this.chatSessionControl.IsDisposed && this.chatSessionControl.SessionChatUser.UserId == chatUser.UserId)
                {
                    this.chatSessionControl.SessionChatUser = chatUser;
                }

                AddUserToSessionList(chatUser);
            }));
        }



        /// <summary>
        /// 显示会话列表
        /// </summary>
        private void ShowChatSession()
        {
            List<ChatUser> users = this.chatBll.GetChatSessionUsers();//获取有会话的用户集合
            foreach (var user in users)
            {
                AddUserToSessionList(user);
            }
        }

        /// <summary>
        /// 添加用户到会话列表容器
        /// </summary>
        /// <param name="chatUser"></param>
        private void AddUserToSessionList(ChatUser chatUser)
        {
            if (!this.flPnlSessionList.Visible) return;

            var lastChatRecord = this.chatBll.GetLastChatRecord(chatUser.UserId);

            ChatUserItemControl chatUserItemControl = this.flPnlSessionList.Get<ChatUserItemControl>(chatUser.UserId);
            if (chatUserItemControl == null)
            {
                ChatUserItemControl chatUserItem = new ChatUserItemControl(chatUser, lastChatRecord?.CreateTime);
                chatUserItem.Name = chatUser.UserId;
                chatUserItem.ItemDoubleClick += ChatUserItem_ItemDoubleClick;
                chatUserItem.ItemClick += ChatUserItem_ItemClick;
                chatUserItem.ContextMenuStrip = this.contextMenuStrip_ChatSession;
                chatUserItem.Width = flPnlSessionList.DisplayRectangle.Width - flPnlSessionList.ScrollBarWidth - flPnlSessionList.ScrollBarHandleWidth;
                this.flPnlSessionList.Add(chatUserItem);
            }
            else//如果控件已存在，那么就更新下数据
            {
                chatUserItemControl.ChatUser = chatUser;
            }

        }

        #endregion 网络发现相关


        #region 右上角扩展按钮

        //设置
        private void btnSetting_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 窗口置顶
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTopMost_Click(object sender, EventArgs e)
        {
            this.btnTopMost.Selected = !this.btnTopMost.Selected;
            this.TopMost = this.btnTopMost.Selected;
        }


        /// <summary>
        /// 设置窗口右上角扩展按钮属性
        /// </summary>
        private void SetBtnHelpProperty()
        {
            this.btnTopMost.BackColor = Setting.Theme.BackColor;
            this.btnTopMost.RectColor = Setting.Theme.BackColor;
            this.btnTopMost.Location = new Point(this.Width - 160, this.btnTopMost.Location.Y);

            this.btnSetting.BackColor = Setting.Theme.BackColor;
            this.btnSetting.RectColor = Setting.Theme.BackColor;
            this.btnSetting.Location = new Point(this.Width - 190, this.btnTopMost.Location.Y);
        }

        private void ChatMainForm_ResizeEnd(object sender, EventArgs e)
        {
            SetBtnHelpProperty();
        }

        private void ChatMainForm_SizeChanged(object sender, EventArgs e)
        {
            SetBtnHelpProperty();
        }

        private void ChatMainForm_UIStyleChanged(object sender, EventArgs e)
        {
            SetBtnHelpProperty();
        }

        #endregion 右上角扩展按钮


        #region 用户列表右键菜单
        private void 查看用户信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripItem toolStripItem = sender as ToolStripItem;
            UIContextMenuStrip contextMenuStrip = toolStripItem.Owner as UIContextMenuStrip;
            if (contextMenuStrip.SourceControl.Tag is ChatUser chatUser)
            {
                using (this.searchAndAddUserForm = new SearchAndAddUserForm())
                {
                    this.searchAndAddUserForm.IsShowSearchGrp = false;
                    this.searchAndAddUserForm.IsShowBtnOkGrp = true;
                    this.searchAndAddUserForm.IsShowUserInfoGrp = true;
                    this.searchAndAddUserForm.IsShowRemarkNamePnl = true;

                    this.searchAndAddUserForm.SetUserInfo(chatUser);
                    this.searchAndAddUserForm.Text = toolStripItem.Text;
                    if (searchAndAddUserForm.ShowDialog() == DialogResult.OK)
                    {
                        this.AddUserToSessionList(searchAndAddUserForm.ChatUser);
                    }
                }
            }
        }


        private void 复制IPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripItem toolStripItem = sender as ToolStripItem;
            UIContextMenuStrip contextMenuStrip = toolStripItem.Owner as UIContextMenuStrip;
            if (contextMenuStrip.SourceControl.Tag is ChatUser chatUser)
            {
                Clipboard.SetText(chatUser.IP);
                this.ShowSuccessTip(this, "已复制IP");
            }
        }


        #endregion 用户列表右键菜单


        #region 聊天会话右键菜单
        private void 删除聊天记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripItem toolStripItem = sender as ToolStripItem;
            UIContextMenuStrip contextMenuStrip = toolStripItem.Owner as UIContextMenuStrip;
            if (contextMenuStrip.SourceControl.Tag is ChatUser chatUser)
            {
                if (!this.ShowAskDialog($"{GlobalData.AppName_zh}-重要操作", $"是否确定删除与【{chatUser.IP}】的聊天记录？", UIStyle.Orange)) return;

                int result = chatBll.DeleteUserRecord(chatUser.UserId);//删除会话记录

                //删除会话项
                ChatUserItemControl chatUserItemControl = this.flPnlSessionList.Get<ChatUserItemControl>(chatUser.UserId);
                if (chatUserItemControl != null)
                {
                    this.flPnlSessionList.Remove(chatUserItemControl);

                    //移除会话窗口
                    if (this.chatSessionControl != null && this.chatSessionControl.SessionChatUser.UserId == chatUser.UserId)
                    {
                        this.chatSessionControl?.Dispose();
                        this.uiSplitContainer.Panel1.Controls.Clear();
                        this.chatSessionControl = null;
                    }
                }

                this.ShowSuccessTip(this, $"已删除{result}聊天记录");
            }
        }

        #endregion 聊天会话右键菜单

        /// <summary>
        /// 设置昵称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtNikeName_TextChanged(object sender, EventArgs e)
        {
            Setting.Chat.NikeName = this.txtNikeName.Text;
        }

        /// <summary>
        /// 关闭窗口事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChatMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.backgroundWorker_SendDiscoveryBroadcast.CancelAsync();
            this.backgroundWorker_SendDiscoveryBroadcast.Dispose();


            #region 卸载注册的一些事件

            ChatBll.ChatUserChangedEvent -= ChatBll_StaticChatUserChangedEvent;
            ChatBll.ChatNewMessageEvent -= this.ChatBll_ChatNewMessageEvent;
            ChatNetworkBll.StartSendDiscoveryBroadcast -= ChatNetworkBll_StartSendDiscoveryBroadcast;
            ChatNetworkBll.CompleteSendDiscoveryBroadcast -= ChatNetworkBll_CompleteSendDiscoveryBroadcast;

            #endregion 卸载注册的一些事件
        }

        private void ChatMainForm_ExtendBoxClick(object sender, EventArgs e)
        {
            AboutHelper.ShowAbout("局域网聊天");
        }
    }

}
